package com.team.bus.module.user.controller;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.zjframework.traceframe.common.controller.BaseController;
import org.zjframework.traceframe.common.dao.util.ConfigUtil;
import org.zjframework.traceframe.common.dao.util.StringUtil;
import org.zjframework.traceframe.common.model.DataGrid;
import org.zjframework.traceframe.common.util.ContextHolderUtils;
import org.zjframework.traceframe.common.util.Encrypt;
import org.zjframework.traceframe.common.util.GetPinyin;
import org.zjframework.traceframe.common.util.JSONUtil;
import org.zjframework.traceframe.common.util.PageHelper;
import com.team.bus.module.common.pagemodel.SessionInfo;
import com.team.bus.module.organization.model.Organization;
import com.team.bus.module.organization.service.IOrganizationService;
import com.team.bus.module.role.model.Role;
import com.team.bus.module.role.service.IRoleService;
import com.team.bus.module.user.model.User;
import com.team.bus.module.user.pagemodel.Puser;
import com.team.bus.module.user.service.IUserService;

@Controller
@RequestMapping("/user")
public class UserController extends BaseController {

	@Autowired
	private IUserService userService;

	@Autowired
	private IRoleService roleService;


	private IOrganizationService organizationService;

	private User user = new User();

	public User getUser() {
		return user;
	}

	public void setUser(User user) {
		this.user = user;
	}


	@RequestMapping("/userslist")
	public String userlist(){

		return "/user/userlist";
	}

	@RequestMapping("/user_datagridlist")
	public void userdatagridlist(HttpSession session,HttpServletRequest request,HttpServletResponse response,Puser puser,PageHelper ph) {
		if (session != null) {
			User user = ((User) session.getAttribute("user"));
			String hql = "from User u where 1=1 and username!='aac' ";
			Map<String, Object> params = new HashMap<>();
			if (!StringUtil.isEmpty(puser.getName())) {
				hql += "  and u.username like :name";
				params.put("name", "%%" + puser.getName() + "%%");
			}
			if (!StringUtil.isEmpty(puser.getOid())) {
				hql += "  and u.organization.id=:organizationid";
				params.put("organizationid", puser.getOid());
				if (!user.getRolename().equals("系统管理员 ")) {
					hql += "  and u.rolename!='系统管理员 '";
				}
			}
				List<User> users = userService.find(hql, ph.getPage(), ph.getRows(), params);
				List<Puser> pusers = new ArrayList<>();
				if (users.size() > 0 && users != null) {
					for (User u : users) {
						Puser p = new Puser();
						BeanUtils.copyProperties(u, p);
						if (u.getOrganization() != null) {
							p.setOid(u.getOrganization().getId());
							p.setOtext(u.getOrganization().getText());
						}
						pusers.add(p);
					}
				}
				DataGrid dg = new DataGrid();
				dg.setTotal(userService.findHql(hql, params).size());
				dg.setRows(pusers);
				super.writeJSON(dg, request, response);

		}
	}

	@RequestMapping("/useraddshow")
	public String useraddshow(){
		return "/user/useradd";
	}

	@RequestMapping("/useradd")
	public void useradd(HttpServletRequest request,HttpServletResponse response,User user){

		super.writeJSON("", request, response);
	}



	/**
	 * @author 赵继
	 * 用户注册模块，密码加密md5
	 */
	@RequestMapping("/reg")
	public void reg(HttpServletRequest request,HttpServletResponse response){
		JSONUtil json = new JSONUtil();
		String name = request.getParameter("name");
		String password = request.getParameter("password");
		user.setUsername(name);
		user.setPassword(Encrypt.e(password));
		try {
			userService.save(user);
			json.setSuccess(true);
			json.setMsg("注册成功");
		} catch (Exception e) {
			e.printStackTrace();
			json.setMsg("注册失败");
		}
		super.writeJSON(json,request,response);
	}

	/**
	 * @author 赵继
	 */
	@RequestMapping("/del")
	public void delete(HttpServletRequest request,HttpServletResponse response,String ids){

		JSONUtil json = new JSONUtil();
		String[] id = ids.split(",");
		StringBuffer hql = new StringBuffer();
		hql.append("delete User where id in(");
		for(int i=0;i<id.length;i++){
			hql.append("'"+id[i]+"'");
			if(id.length>0 && id.length-1!=i){
				hql.append(",");
			}
		}
		hql.append(")");
		try {
			userService.executeHql(hql.toString());
			json.setSuccess(true);
			json.setMsg("删除成功");
		} catch (Exception e) {
			e.printStackTrace();
			json.setMsg("删除失败:"+e.getMessage());
		}
		super.writeJSON(json,request,response);
	}

	/**
	 * @author 赵继
	 */
	@RequestMapping("/save")
	public void save(HttpServletRequest request,HttpServletResponse response,Puser puser){

		JSONUtil json = new JSONUtil();
			try {
				if(puser!=null){
					BeanUtils.copyProperties(puser, user);
					Organization organization = this.organizationService.get(Organization.class, puser.getOid());
					user.setPinyin(GetPinyin.getPinYinHeadChar(puser.getName()).toString());

					user.setPassword(Encrypt.e("123456"));
					user.setRoles(new HashSet<Role>());
					user.setOrganization(organization);
					user.setUserType(organizationService.getozpid(puser.getOid()));
					user.setRolename("");
					user = userService.saveInsertRow(user);
					json.setSuccess(true);
					json.setMsg("操作成功");
					puser.setId(user.getId());
					puser.setOtext(user.getOrganization().getText());
					json.setObj(puser);
				}
			} catch (Exception e) {
				e.printStackTrace();
				json.setMsg(e.getMessage());
			}
		super.writeJSON(json,request,response);
	}

	/**
	 * @author 赵继
	 */
	@RequestMapping("/editTo")
	public String editTo(HttpSession session,HttpServletRequest request,HttpServletResponse response,Puser puser,String id){

			user = userService.get(User.class, id);
			BeanUtils.copyProperties(user, puser);
			request.setAttribute("puser", puser);
            request.setAttribute("user", user);
			request.setAttribute("oid", puser.getOid());

		return "/user/userEdit";
	}

	/**
	 * @author 赵继
	 */
	@RequestMapping("/greditTo")
	public String greditTo(HttpSession session,HttpServletRequest request,HttpServletResponse response,Puser puser,String id){

			user = userService.get(User.class, ((User)session.getAttribute("user")).getId());
			BeanUtils.copyProperties(user, puser);
			request.setAttribute("puser", puser);
			request.setAttribute("oid", puser.getOid());

		return "/user/userEdit";
	}

	/**
	 * @author 赵继
	 */
	@RequestMapping("/edit")
	public void edit(HttpSession session,HttpServletRequest request,HttpServletResponse response,Puser puser){

		JSONUtil json = new JSONUtil();
			try {
				if(puser!=null){
					BeanUtils.copyProperties(puser, user);
					if(puser.getOid()!=null){
						Organization organization = this.organizationService.get(Organization.class, puser.getOid());
						user.setUserType(organizationService.getozpid(puser.getOid()));
						user.setOrganization(organization);
					}
					Role role = new Role();
					Set<Role> roles = new HashSet<Role>();
					if(!puser.getRoleIds().isEmpty()){
						String roleIds = puser.getRoleIds();
						String []roleIdArray = roleIds.split(",");
						for(String roleId : roleIdArray){
							role = roleService.get(Role.class, roleId);
							roles.add(role);
						}
					}
					user.setRoles(roles);
					user.setPinyin(GetPinyin.getPinYinHeadChar(puser.getName()).subSequence(0, 1).toString());
					user = userService.updateRow(user);
					json.setSuccess(true);
					json.setMsg("编辑成功");
					puser.setId(user.getId());
					puser.setOtext(user.getOrganization().getText());
					json.setObj(puser);
					//session.setAttribute("user",user);

				}
			} catch (Exception e) {
				e.printStackTrace();
				json.setMsg(e.getMessage());
			}
		super.writeJSON(json,request,response);
	}


	/**
	 * @author 赵继
	 * @param request
	 * @param response
	 * 用户登录
	 */
	@RequestMapping("/login_easyui")
	public void login_easyui(HttpServletRequest request,HttpServletResponse response){
		String name = request.getParameter("name");
		String password = request.getParameter("password");
		JSONUtil json = new JSONUtil();
		List<User> userss = new ArrayList<User>();
		if(!StringUtil.isEmpty(name) && !StringUtil.isEmpty(password)){
			try {
				String hql = "from User where username=? and password=?";
				userss = userService.findHql(hql,name,Encrypt.e(password));
			} catch (Exception e) {
				e.printStackTrace();
				json.setMsg(e.getMessage());
			}
			if(userss.size()>0){
				json.setSuccess(true);
				json.setMsg("登录成功");

				SessionInfo sessionInfo = new SessionInfo();
				BeanUtils.copyProperties(userss.get(0), sessionInfo);
				sessionInfo.setOid(userss.get(0).getOrganization().getId());
				Map<String,Object> param = new HashMap<>();
				user = userss.get(0);
				param.put("id", user.getId());
				String hql = "from User u join fetch u.roles role join fetch role.menus menu where u.id =:id";
				sessionInfo.setResourceList(userService.gainMenus(hql, param));
				ContextHolderUtils.getSession().setAttribute(ConfigUtil.getSessionInfoName(), sessionInfo);
				/*json.setObj(sessionInfo);*/
			}else{
				json.setMsg("登录失败");
			}
		}
		super.writeJSON(json,request,response);
	}




	@RequestMapping("/loginTo")
	public String loginTo(HttpServletRequest request,HttpServletResponse response){
			return "/login/login";
	}

	@RequestMapping("/logintoshow")
	public String logintoshow(HttpSession session){
		if(session.getAttribute("user")!=null){
			return "/index_easyui";
		}
		return "/login/login";
	}



	/**
	 * @author 赵继
	 * @param request
	 * @param response
	 * 异步用户登录
	 */
	@RequestMapping(value="/logins",method = RequestMethod.POST)
	@ResponseBody
	public JSONUtil  login4ajax(HttpSession session,
								HttpServletRequest request,
								HttpServletResponse response,
								String username,
								String password){
		String msg = "";
		JSONUtil json = new JSONUtil();
		List<User> userss = new ArrayList<User>();
		if(!StringUtil.isEmpty(username) && !StringUtil.isEmpty(password)){
			try {
				String hql = "from User where username=? and password=?";
				userss = userService.findHql(hql,username,password);
			} catch (Exception e) {
				e.printStackTrace();
				json.setMsg(e.getMessage());
			}
			if(userss.size()>0){
				SessionInfo sessionInfo = new SessionInfo();
				BeanUtils.copyProperties(userss.get(0), sessionInfo);
				if(userss.get(0).getOrganization() !=null){
					sessionInfo.setOid(userss.get(0).getOrganization().getId());
				}
				session.setAttribute(ConfigUtil.getSessionInfoName(), sessionInfo);
				session.setAttribute("user", userss.get(0));
				msg = "登录成功！";
				json.setMsg(msg);
				json.setSuccess(true);
				return json;
			}else{
				msg = "用户名或密码输入错误,请重新输入！";
				json.setMsg(msg);
				json.setSuccess(false);
				return json;
			}
		}else{
			msg = "用户名密码不能为空,请重新输入！";
			json.setMsg(msg);
			json.setSuccess(false);
			return json;
		}
	}

	/**
	 * @author 赵继
	 * 转向角色列表页
	 */
	@RequestMapping("/roleTreePage")
	public String roleTreePage(HttpServletRequest request,HttpServletResponse response,String id){
		List<User> users = new ArrayList<User>();
		String[] ids = id.split(",");
		String userids = "";
		String roleIds = "";
		for(int i=0; i < ids.length; i++){
			User user = userService.get(User.class, ids[i]);

			if(ids.length-1==i){
				userids += user.getId();
				if(!roleIds.contains(user.getId())){
					roleIds += user.getRoleIds();
				}
			}else{
				userids += user.getId()+",";
				if(!roleIds.contains(user.getId())){
					roleIds += user.getRoleIds()+",";
				}
			}
			users.add(user);
		}

		request.setAttribute("users", users);
		request.setAttribute("userids", userids);
		request.setAttribute("roleIds", roleIds);
		return "/role/roleTree4batch";
	}

	/**
	 * @author 赵继
	 * 给用户设定角色
	 */
	@RequestMapping("/grantRole4user")
	public void grantRole(HttpServletRequest request,HttpServletResponse response,Puser pu,String roleIds,String userids){

		JSONUtil json = new JSONUtil();
			try {
					String[] useridss = userids.split(",");
					for(String uid : useridss){
						user  = new User();
						User tempuser = userService.get(User.class, uid);
						BeanUtils.copyProperties(tempuser, user);
						Set<Role> roleSet = new HashSet<Role>();
						user.setRoleIds(roleIds);
						String rolename = "";
						for (String roleId : roleIds.split(",")) {
							if (!StringUtils.isBlank(roleId)) {
								Role role = roleService.get(Role.class, roleId);
								rolename  += role.getText()+" ";
								if (role != null) {
									roleSet.add(role);
								}
							}
						}
							user.setRolename(rolename);
							user.setRoles(roleSet);
							userService.updateRows(user);
					}
					json.setSuccess(true);
					json.setMsg("用户批量授权成功");
			} catch (Exception e) {
				e.printStackTrace();
				json.setMsg("用户批量授权失败  原因："+e.getMessage());
			}
		super.writeJSON(json,request,response);
	}

	/**
	 * 个人信息查看
	 *
	 */
	@RequestMapping("/userinfo")
	public String userinfo(){
		SessionInfo sessionInfo = new SessionInfo();
		sessionInfo = (SessionInfo) ContextHolderUtils.getSession().getAttribute(ConfigUtil.getSessionInfoName());
		if(StringUtil.isNotEmpty(sessionInfo.getId())){
			User user = userService.get(User.class, sessionInfo.getId());
			ContextHolderUtils.getServletContext().setAttribute("user", user);
		}
		return "/user/userInfo";
	}

	/**
	 * 跳转到编辑自己的密码页面
	 *
	 * @return
	 */
	@RequestMapping("/editCurrentUserPwdPage")
	public String editCurrentUserPwdPage() {
		return "/user/userEditPwd";
	}

	/**
	 * 修改自己的密码
	 *
	 * @param session
	 * @param pwd
	 * @return
	 */
	@RequestMapping("/editCurrentUserPwd")
	public void editCurrentUserPwd(HttpSession session, String oldPwd, String pwd,HttpServletRequest request,HttpServletResponse response) {
		JSONUtil j = new JSONUtil();
		if (session != null) {
			SessionInfo sessionInfo = (SessionInfo) session.getAttribute(ConfigUtil.getSessionInfoName());
			if (sessionInfo != null) {
				if (userService.editCurrentUserPwd(sessionInfo, oldPwd, pwd)) {
					j.setSuccess(true);
					j.setMsg("编辑密码成功，下次登录生效！");
				} else {
					j.setMsg("原密码错误！");
				}
			} else {
				j.setMsg("登录超时，请重新登录！");
			}
		} else {
			j.setMsg("登录超时，请重新登录！");
		}
		super.writeJSON(j,request,response);
	}

	/**
	 * 退出登录
	 *
	 * @param session
	 * @return
	 */
	@RequestMapping("/logout")
	public void logout(HttpSession session,HttpServletRequest request,HttpServletResponse response) {
		JSONUtil json = new JSONUtil();
		if (session != null) {
			session.invalidate();
		}
		json.setSuccess(true);
		json.setMsg("注销成功！");
		super.writeJSON(json,request,response);
	}

	/**
	 * 用户的comboxgrid
	 *
	 * @return
	 */
	@RequestMapping("/userComboxGrid")
	@ResponseBody
	public List<Puser> userComboxGrid(String q) {
		String hql = "from User where pinyin like '%"+q+"%' ";
		Map<String,Object> param = new HashMap<String,Object>();
		List<User> users = userService.findHql(hql, param);
		List<Puser> pusers = new ArrayList<>();
		if(users.size()>0 && users!=null){
			for(User u : users){
				Puser p = new Puser();
				BeanUtils.copyProperties(u, p);
				if(u.getOrganization()!=null){
					p.setOid(u.getOrganization().getId());
					p.setOtext(u.getOrganization().getText());
				}
				pusers.add(p);
			}
		}
		return pusers;
	}

    /**
     * 检测用户名是否存在
     *
     * @return
     */
    @RequestMapping("/isUserNameExist")
    @ResponseBody
    public JSONUtil isUserNameExist(String q) {
        JSONUtil json = new JSONUtil();
        String hql = "from User where username=:username";
        Map<String,Object> param = new HashMap<String,Object>();
        param.put("username" , q);
        List<User> users = userService.findHql(hql, param);
        List<Puser> pusers = new ArrayList<>();
        if(users.size()>0){
            json.setMsg("此用户名已经存在请重新填写!");
            json.setSuccess(false);
        }else if(users.size()==0){
            json.setSuccess(true);
        }
        return json;
    }


    /**
     * 转到index页面
     *
     * @return
     */
    @RequestMapping("/toIndex")
    public String toIndex(HttpSession session) {
        if(session.getAttribute("user")!=null){
            return "index";
        }
        return "/login/login";
    }

}
